import type { Server as HttpServer } from 'http';
import { Server, Namespace, Socket } from 'socket.io';
import { verifyAccessToken } from '@/helpers/tokenVerify';
import { EventTypes } from './const';

type HanderType = (s: Socket) => void;

export class SocketPlus {
  private io: Server;
  public nsp: Namespace;
  private server: HttpServer;
  private handlers: HanderType[] = [];

  constructor(server: HttpServer) {
    this.server = server;
  }

  public add = (handler: HanderType) => {
    this.handlers.push(handler);
    return this;
  }

  private connection = async (ctx: Socket) => {
    const { accessToken } = ctx.handshake.auth;
    let result = await verifyAccessToken(accessToken);

    // 校验token是否过期
    if (result === false) {
      ctx.emit(EventTypes.tokenVail);
      ctx.disconnect();
    } else {
      ctx.join(result.userId);
      ctx.userId = result.userId;
      this.handlers.forEach(h => h(ctx));
    }
  }

  public start = () => {
    this.io = new Server(this.server);
    this.nsp = this.io.of('/');
    this.nsp.on('connection', this.connection);
  }
}